package org.example.service;

import lombok.extern.slf4j.Slf4j;
import org.example.config.EmailConfig;
import org.example.dto.RegisterDTO;
import org.example.entity.User;
import org.example.entity.VerifyCode;
import org.example.mapper.UserMapper;
import org.example.mapper.VerifyCodeMapper;
import org.example.utils.JwtUtil;
import org.example.utils.PasswordEncoder;
import org.example.utils.VerifyCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class UserService {
    
    private static final int VERIFY_CODE_LENGTH = 4;
    private static final int VERIFY_CODE_EXPIRE_MINUTES = 5;
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private VerifyCodeMapper verifyCodeMapper;
    
    @Autowired
    private JavaMailSender mailSender;
    
    @Autowired
    private EmailConfig emailConfig;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    @Autowired
    private JwtUtil jwtUtil;

    //注册
    @Transactional(rollbackFor = Exception.class)
    public boolean register(RegisterDTO registerDTO) {
        // 验证验证码
        List<VerifyCode> verifyCodes = verifyCodeMapper.selectList(registerDTO.getEmail());
        if (verifyCodes.isEmpty()) {
            log.warn("验证码不存在，邮箱: {}", registerDTO.getEmail());
            return false;
        }
        
        VerifyCode verifyCode = verifyCodes.get(0);
        if (!verifyCode.getCode().equals(registerDTO.getVerifyCode())) {
            log.warn("验证码不正确，邮箱: {}", registerDTO.getEmail());
            return false;
        }
        
        if (verifyCode.getExpireTime().isBefore(LocalDateTime.now())) {
            log.warn("验证码已过期，邮箱: {}", registerDTO.getEmail());
            return false;
        }
        
        // 创建用户
        User user = new User();
        user.setEmail(registerDTO.getEmail());
        // 对密码进行加密
        user.setPassword(passwordEncoder.encode(registerDTO.getPassword()));
        
        int result = userMapper.insert(user);
        
        // 删除已使用的验证码
        verifyCodeMapper.deleteByEmail(registerDTO.getEmail());
        
        log.info("用户注册成功，邮箱: {}", registerDTO.getEmail());
        return result > 0;
    }
    
    //发送验证码
    @Transactional(rollbackFor = Exception.class)
    public boolean sendVerifyCode(String email) {
        // 生成验证码
        String code = VerifyCodeUtils.generateVerifyCode(VERIFY_CODE_LENGTH);
        
        // 删除旧验证码
        verifyCodeMapper.deleteByEmail(email);
        
        // 保存新验证码
        VerifyCode verifyCode = new VerifyCode();
        verifyCode.setEmail(email);
        verifyCode.setCode(code);
        verifyCode.setExpireTime(LocalDateTime.now().plusMinutes(VERIFY_CODE_EXPIRE_MINUTES));
        
        int result = verifyCodeMapper.insert(verifyCode);
        
        if (result > 0) {
            // 发送邮件
            sendEmail(code, email);
            //log.info("验证码发送成功，邮箱: {}", email);
            return true;
        } else {
            //log.error("验证码保存失败，邮箱: {}", email);
            return false;
        }
    }
    
    //发送邮件
    public void sendEmail(String verifyCode, String email) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(emailConfig.getUserName());
            message.setTo(email);
            message.setSubject("注册验证码");
            message.setText("您的验证码是：" + verifyCode + "，5分钟内有效。");
            
            mailSender.send(message);
            log.info("邮件发送成功，收件人: {}", email);
        } catch (Exception e) {
            log.error("邮件发送失败，收件人: {}，错误信息: {}", email, e.getMessage());
        }
    }
    
    // 登录
    public String login(String email, String password) {
        List<User> users = userMapper.selectByEmail(email);
        if (users.isEmpty()) {
            log.warn("用户不存在，邮箱: {}", email);
            return null;
        }
        
        User user = users.get(0);
        // 使用PasswordEncoder验证密码
        if (!passwordEncoder.matches(password, user.getPassword())) {
            log.warn("密码错误，邮箱: {}", email);
            return null;
        }
        
        log.info("用户登录成功，邮箱: {}", email);
        // 生成JWT令牌
        return jwtUtil.generateToken(email);
    }
}